<template>
  <div class="material-report-container">
    <!-- 顶部筛选区 -->
    <div class="filter-container">
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" class="filter-form" label-width="70px">
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="日期范围" class="filter-form-item wide">
                <el-date-picker v-model="filterForm.timeList" type="datetimerange" range-separator="~"
                  start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料代码" class="filter-form-item">
                <el-select multiple v-model="filterForm.skuID" placeholder="请选择物料信息" clearable remote
                  :remote-method="searchSelectNccMaterial" filterable>
                  <el-option v-for="item in materialNameOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-switch v-model="filterForm.modeCode" active-text="按编码" inactive-text="按名称" :active-value="1"
                  :inactive-value="0"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="仓库" class="filter-form-item">
                <el-select clearable multiple filterable v-model="filterForm.wareHouseID" placeholder="请选择仓库">
                  <el-option v-for="item in NccStockOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货单号" class="filter-form-item wide">
                <el-input placeholder="请输入发货单号" v-model="filterForm.vbillsCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出库单号" class="filter-form-item wide">
                <el-input placeholder="请输入出库单号" v-model="filterForm.wareHouseOutBills"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="运输方式" class="filter-form-item wide">
                <el-input placeholder="请输入运输方式" v-model="filterForm.shippingMethod"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="批次号" class="filter-form-item">
                <div style="display: flex; gap: 8px; width: 100%;">
                  <el-input clearable v-model="filterForm.batchNo" placeholder="请输入批次号" style="flex: 1;"></el-input>
                  <el-dropdown @command="handleCommandCode" trigger="click">
                    <span class="el-dropdown-link">
                      {{btnCode}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="0">全部</el-dropdown-item>
                      <el-dropdown-item command="1">等于</el-dropdown-item>
                      <el-dropdown-item command="2">不等于</el-dropdown-item>
                      <el-dropdown-item command="3">包含</el-dropdown-item>
                      <el-dropdown-item command="4">不包含</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 操作按钮 -->
              <el-form-item class="filter-form-item" style="flex-basis: 100%;">
                <div class="action-buttons">
                  <el-button type="primary" icon="el-icon-search" @click="fetchBasicData">查询</el-button>
                  <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出excel</el-button>
                  <el-button type="primary" icon="el-icon-download" @click="exportPdf">导出pdf</el-button>
                  <el-button type="primary" icon="el-icon-download" @click="exportCsv">导出CSV</el-button>
                  <el-button type="danger" icon="el-icon-refresh" @click="resetFilter">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- 主内容区 -->
    <div class="main-content">
      <el-table height="calc(100vh - 280px)" :data="sluggishStatistic" border style="width: 100%">
        <el-table-column prop="dmakedate" label="发货日期">
          <template #default="{row}">
            {{formatAllDate(row.dmakedate)}}
          </template>
        </el-table-column>
        <el-table-column prop="cmaterialoid_code" label="代码" />
        <el-table-column prop="graphid" label="GMP码" />
        <el-table-column prop="vbcdef2" label="供应商代码" />
        <el-table-column prop="cmaterialoid_name" label="产品名称" />
        <el-table-column prop="materialtype" label="规格" />
        <el-table-column prop="vbatchcode" label="批号" />
        <el-table-column prop="nnum" label="发货主数量" />
        <el-table-column prop="cunitid_name" label="主单位" />
        <el-table-column prop="nassistnum" label="发货数量" />
        <el-table-column prop="castunitid_name" label="单位" />
        <el-table-column prop="ccustomerid_name" label="收货单位（商业客户）" />
        <el-table-column prop="vdef21" label="物流公司" />
        <el-table-column prop="vdef10" label="地址" />
        <el-table-column prop="vdef7" label="收货人" />
        <el-table-column prop="vdef8" label="收货人联系方式" />
        <el-table-column prop="vdef47_name" label="运输方式" />
        <el-table-column prop="vdef26" label="发货单号" />
        <el-table-column prop="vbillcode" label="出库单号" />
        <el-table-column prop="cwarehouseid_name" label="仓库" />
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background layout=" total,prev, pager, next, sizes,jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="filterForm.pageNum" :page-size="filterForm.pageSize"
        :page-sizes="[20, 50,100]" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  // 引入下拉框方法组件
  import SearchSelect from "@/views/components/dropDown/searchSelect.js";
  import {
    getAllWarehouseList, //获取仓库下拉
  } from "@/api/index/warehouse";
  import BasicStatistics from './components/BasicStatistics'
  import {
    wmsReportDeliveryStatistic, //获取统计数量
    getnccMaterial, //获取物料
  } from '@/api/report/allNews'
  export default {
    name: 'MaterialReport',
    components: {
      BasicStatistics,
    },
    data() {
      return {
        btnCode: '全部',
        filterForm: {
          skuID: [], //商品
          wareHouseID: [], //仓库
          batchNo: '', //批号
          batchNoValue: 0, //0等于任意一个 1等于 2不等于 3包含 4不包含
          pageNum: 1,
          pageSize: 20,
          modeCode: 0,
          shippingMethod: '', //运输方式
          timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()],
          vbillsCode: '',
          wareHouseOutBills: '', //出库单号
        },
        // 数据加载状态
        basicLoading: false,
        // 数据
        sluggishStatistic: [],
        NccStockOptions: [], //仓库下拉
        total: 0,
        materialNameOptions: []
      }
    },
    created() {
      this.fetchBasicData();
    },
    mounted() {
      this.searchNCCStockList();
    },
    methods: {
      //导出excel
      exportExcel() {
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          beginDate,
          endDate,
          wareHouseOutBills: this.filterForm.wareHouseOutBills, //出库单号
          vbillsCode: this.filterForm.vbillsCode, //发货单号
          shippingMethod: this.filterForm.shippingMethod, //运输方式
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportReportDeliveryStatistic', {
          ...params
        }, `产品发运记录.xlsx`)
      },
      //导出pdf
      exportPdf() {
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          beginDate,
          endDate,
          wareHouseOutBills: this.filterForm.wareHouseOutBills, //出库单号
          vbillsCode: this.filterForm.vbillsCode, //发货单号
          shippingMethod: this.filterForm.shippingMethod, //运输方式
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportPdfReportDeliveryStatistic', {
          ...params
        }, `产品发运记录.pdf`)
      },
      //导出CSV
      exportCsv() {
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          batchNo: this.filterForm.batchNo, //批号
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          beginDate,
          endDate,
          wareHouseOutBills: this.filterForm.wareHouseOutBills, //出库单号
          vbillsCode: this.filterForm.vbillsCode, //发货单号
          shippingMethod: this.filterForm.shippingMethod, //运输方式
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportCsvReportDeliveryStatistic', {
          ...params
        }, `产品发运记录.csv`)
      },
      // 1、获取NCC仓库信息
      searchNCCStockList() {
        SearchSelect.searchNCCStockList(this)
          .then(() => {
            // 获取到仓库信息后，更新 NccStockOptions
            this.NccStockOptions = this.NccStockList.map((item) => ({
              label: item.label,
              value: item.value,
            }));
          })
      },
      // 格式化时间
      formatAllDate(date) {
        if (!date) return ''; // 如果 `date` 为空或 `null`，返回占位符
        return this.$dayjs(date).isValid() ? this.$dayjs(date).format('YYYY-MM-DD') : '-';
      },
      // 远程搜索函数 获取NCC物料信息
      searchSelectNccMaterial(query) {
        if (query !== '') {
          const params = {
            materialName: query, // 传入输入的关键字
            modeCode: this.filterForm.modeCode, // 传入输入的关键字
          };
          // 调用接口进行物料信息查询
          getnccMaterial(params)
            .then(response => {
              if (response.code === 200) {
                // 更新物料选项
                this.materialNameOptions = response.data
              } else {
                this.materialNameOptions = [];
              }
            })
            .catch(error => {
              console.error('查询物料信息失败:', error);
              this.materialNameOptions = [];
            })
            .finally(() => {});
        } else {
          this.materialNameOptions = [];
        }
      },
      //分页
      handleSizeChange(val) {
        this.filterForm.pageSize = val;
        this.filterForm.pageNum = 1;
        this.fetchBasicData();
      },
      handleCurrentChange(val) {
        this.filterForm.pageNum = val;
        this.fetchBasicData();
      },
      handleCommandCode(command) {
        if (command == 0) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '全部';
          this.fetchBasicData();
        } else if (command == 1) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '等于';
          this.fetchBasicData();
        } else if (command == 2) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不等于';
          this.fetchBasicData();
        } else if (command == 3) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '包含';
          this.fetchBasicData();
        } else {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不包含';
          this.fetchBasicData();
        }
      },
      resetFilter() {
        this.filterForm = {
            skuID: [], //商品
            wareHouseID: [], //仓库
            batchNo: '', //批号
            batchNoValue: 0, //0等于任意一个 1等于 2不等于 3包含 4不包含
            pageNum: 1,
            pageSize: 20,
            modeCode: 0,
            shippingMethod: '', //运输方式
            timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()],
            vbillsCode: '',
            wareHouseOutBills: '', //出库单号
          },
          this.fetchBasicData()
      },
      //获取日期
      getDefaultStartDate() {
        const date = new Date()
        date.setMonth(date.getMonth() - 1)
        return this.formatDate(date)
      },
      getDefaultEndDate() {
        return this.formatDate(new Date())
      },
      //格式化日期
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },
      async fetchBasicData() {
        this.basicLoading = true;
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];
        try {
          const params = {
            skuID: this.filterForm.skuID.join(','), //商品
            wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
            batchNo: this.filterForm.batchNo, //批号
            batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
            beginDate,
            endDate,
            wareHouseOutBills: this.filterForm.wareHouseOutBills, //出库单号
            vbillsCode: this.filterForm.vbillsCode, //发货单号
            shippingMethod: this.filterForm.shippingMethod, //运输方式
            pageNum: this.filterForm.pageNum,
            pageSize: this.filterForm.pageSize,
          };
          wmsReportDeliveryStatistic(params).then(res => {
            this.sluggishStatistic = res.data.rows;
            this.total = res.data.total;
          });
        } catch (error) {
          console.error('获取基础统计数据失败:', error);
          this.$message.error('获取数据失败');
        } finally {
          this.basicLoading = false;
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .material-report-container {
    padding: 16px;
    background-color: #f5f7fa;
  }

  .filter-container {
    margin-bottom: 16px;
  }

  .filter-card {
    border-radius: 4px;
  }

  .range-inputs {
    display: flex;

    ::v-deep .el-input--medium .el-input__inner {
      width: 135px;
    }
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    display: flex;
    align-items: center;
  }

  .el-dropdown-link i {
    margin-left: 4px;
  }

  .el-form-item__label {
    padding-right: 8px;
  }

  .main-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
</style>
